package net.caixiaomi.info.util;

import android.app.KeyguardManager;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v4.os.CancellationSignal;

import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.logger.Timber;

/**
 * 指纹工具
 */

public class FingerprintUtil {
    public static CancellationSignal cancellationSignal;

    public static void callFingerPrint(final FingerprintManagerCompat.AuthenticationCallback listener) {
        FingerprintManagerCompat managerCompat = FingerprintManagerCompat.from(CommonApp.getInstance());
        if (!isSupportFinger(managerCompat)) { //判断设备是否支持
            return;
        }
        cancellationSignal = new CancellationSignal(); //必须重新实例化，否则cancel 过一次就不能再使用了
        managerCompat.authenticate(null, 0, cancellationSignal, listener, null);
    }

    public static void cancel() {
        if (cancellationSignal != null)
            cancellationSignal.cancel();
    }

    public static boolean isSupportFinger(FingerprintManagerCompat managerCompat) {
        try {
            KeyguardManager keyguardManager = (KeyguardManager) CommonApp.getInstance().getSystemService(CommonApp.getInstance().KEYGUARD_SERVICE);
            Timber.d("managerCompat.isHardwareDetected() = "+ managerCompat.isHardwareDetected());
            Timber.d("keyguardManager.isKeyguardSecure() = "+ keyguardManager.isKeyguardSecure());
            Timber.d("managerCompat.hasEnrolledFingerprints() = "+ managerCompat.hasEnrolledFingerprints());
            return managerCompat.isHardwareDetected() && keyguardManager.isKeyguardSecure() && managerCompat.hasEnrolledFingerprints();//判断设备是否支持
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
